package com.rimi.servlet;

import com.rimi.bean.UserBean;
import com.rimi.service.UserService;
import com.rimi.service.impl.UserServiceImpl;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserService userService;

    private static final String REMBERME="1";

    public LoginServlet(){
        userService=new UserServiceImpl();
        System.out.println("创建servlet对象");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //跳转登录页面
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //先获取验证码
        String code = request.getParameter("code");
        if (!CaptchaUtil.ver(code, request)) {
            CaptchaUtil.clear(request);
            //
            request.setAttribute("msg","验证码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
        //接收登录信息
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        //调用业务层
        UserBean userBean = userService.login(email, password);
        //对返回结果进行判断
        if(userBean == null){
            request.setAttribute("msg","账号或密码错误");
            //跳转登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }

        //用户是否记住我、七天免登录
        String remberme = request.getParameter("remberme");
        if(REMBERME.equals(remberme)){
            //用户选择了七天免登录
            //将用户的登录信息存储到cookie中
            String token = UUID.randomUUID().toString();
            //按照当前的时间 加上 七天 获取到时间
            userService.saveTokenByUserId(userBean.getUserId(),token);
            //保存到用户的浏览器
            Cookie rememberMe = new Cookie("rememberMe",token);
            //cookie存活时间
            rememberMe.setMaxAge(60*60*24*7);
            //
            response.addCookie(rememberMe);
        }
        //jrebel
        //将用户信息存储到session中
        request.getSession().setAttribute("user",userBean);
        //跳转页面、做出响应
        //登录成功
        response.sendRedirect("/v2/index");
    }

}
